from django.shortcuts import render, redirect, HttpResponse
from django.views.generic import View
from apps.home_page.models import UdwShoppingCart, UdwUser, UdwGoods, UdwGoodsInfo
from django.http import JsonResponse
import datetime
from django.db.models import Q



#购物车
class Shop_cart(View):
    def get(self, request):
        user_id = request.session.get('id')
        if not user_id:
            return redirect('login_register:login')
        user = UdwUser.objects.get(user_id=user_id)
        s_carts = UdwShoppingCart.objects.filter(user_id=user_id)     #当前用户购物车订单
        carts = []
        for scat in s_carts:
            try:
                #当前购物车商品的详细信息
                good_info = UdwGoodsInfo.objects.get(goods_info_id=scat.goods_info_id)
                #商品的名字
                good_name = UdwGoods.objects.get(goods_id=good_info.goods_id).goods_name
                good = {good_name: good_info}
                info = {}
                info[scat] = good
                carts.append(info)
            except UdwGoodsInfo.DoesNotExist:
                pass
        print(carts)
        return render(request, 'udai_shopcart.html', {'username': user.user_phone,
                                                      'carts': carts})

    def post(self, request):
        num = request.POST.get('checked')
        print(num)
        return HttpResponse('1')


#修改购物车商品数量
class Shop_Cart_Update(View):
    def post(self, request):
        #1.获取参数
        user_id = request.session.get('id')
        cart_id = request.POST.get('cart_id')
        count = request.POST.get('count')
        print(user_id, cart_id, count)
        #2.校验参数完整性
        if not all([user_id, cart_id, count]):
            return JsonResponse({'error': 1, 'error_msg': '参数不完整'})
        #3.校验商品数量是否合法
        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({'error': 2, 'error_msg': '商品数量不合法'})
        #4.校验商品是否存在
        cart = UdwShoppingCart.objects.get(cart_id=cart_id)   #购物车商品id
        try:
            sku = UdwGoodsInfo.objects.get(goods_info_id=cart.goods_info_id)
        except UdwGoodsInfo.DoesNotExist:
            return JsonResponse({'error': 3, 'error_msg': '商品不存在'})
        #5.更新购物车的总件数
        if sku.goods_info_num >= count:
            cart.number = count
            cart.save()
        else:
            return JsonResponse({'error': 4, 'error_msg': '商品数量不足'})
        #获取更新后的购物车中的总件数
        total_count = cart.number
        return JsonResponse({'error': 'ok', 'total_count': total_count, 'error_msg': '更新成功'})


# """购物车添加"""
class CartAddView(View):
    def post(self, request):
        user_id = request.session.get('id')
        if not user_id:
            return redirect('login_register:login')
        g_id = request.POST.get('id')
        count = request.POST.get('count')
        color = request.POST.get('color')
        size = request.POST.get('size')
        print(count, color, size)
        if not all([g_id, count, color, size]):
            return JsonResponse({"errno": 1, "error_msg": "参数不完整"})
        try:
            count = int(count)
        except Exception as e:
            return JsonResponse({"errno": 2, "error_msg": "输入商品数量信息不合法"})
        try:
            goods_info = UdwGoodsInfo.objects.get(Q(goods_id=g_id)&Q(goods_info_color=color)&Q(goods_info_size=size))    #当前商品的详细信息
        except UdwGoodsInfo.DoesNotExist:
            return JsonResponse({"errno": 0, "error_msg": "商品不存在"})

        if count > goods_info.goods_info_num:
            return JsonResponse({"errno": 3, "error_msg": "商品数量不合法"})
        #判断购物车中是否存在此商品，
        # 判断颜色，尺码是否相同,如果存在则只添加商品数量即可，
        # 如果没有则添加商品数量和信息
        s_cart = UdwShoppingCart.objects.filter(goods_info_id=goods_info.goods_info_id)  #判断是否有此商品的订单
        if s_cart:
            if len(s_cart) == 1:
                s_cart[0].number += count
                s_cart[0].save()
        else:
            UdwShoppingCart.objects.create(user_id=user_id, goods_info_id=goods_info.goods_info_id, number=count,
                                        price=goods_info.goods_info_price,
                                        time=datetime.datetime.now())
        total_count = len(UdwShoppingCart.objects.all())
        return JsonResponse({"errno": 'ok', "error_msg": "添加成功", 'total_count': total_count})



#购物车删除
class DelCartView(View):
    def post(self, request):
        user_id = request.session.get('id')
        cart_id = request.POST.get('cart_id')
        #参数是否完整
        if not all([user_id, cart_id]):
            return JsonResponse({'error': 1, 'error_msg': '参数不完整'})
        #订单商品是否存在
        cart = UdwShoppingCart.objects.get(cart_id=cart_id)
        try:
            goods_info = UdwGoodsInfo.objects.get(goods_info_id=cart.goods_info_id)
        except UdwGoodsInfo.DoesNotExist:
            return JsonResponse({'error': 2, 'error_msg': "商品不存在"})
        #删除订单
        cart.delete()
        #获取当前用户购物车的件数
        count = UdwShoppingCart.objects.filter(user_id=user_id).count()
        return JsonResponse({"error": 'ok', 'total_count': count, 'error_msg': '删除成功'})
